package com.kcnet.qk.controller.addfriend;

import android.util.Log;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;

import com.kcnet.qk.constant.Const;
import com.kcnet.qk.controller.BasePeopleController;
import com.kcnet.qk.util.NodeUtil;
import com.kcnet.qk.util.PreferenceHelper;
import com.kcnet.qk.util.RootShell;

import org.greenrobot.eventbus.EventBus;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.jesse.nativelogger.NLogger;

/**
 * Created by Administrator on 2018/7/9.
 * 通过好友请求
 */

public class AddAdopCTR extends BasePeopleController {
    private static String TAG = "通过好友请求";

    private int mType;
    private String mClassName;

    private static AddAdopCTR mRongCloudInstance;
    protected Map<String, Boolean> mRecordMap = Collections.synchronizedMap(new HashMap());
    private String text;
    /**
     * 获取RongCloud 实例。
     *
     * @return RongCloud。
     */
    public static AddAdopCTR getInstance() {
        if (mRongCloudInstance == null) {
            synchronized (AddAdopCTR.class) {

                if (mRongCloudInstance == null) {
                    mRongCloudInstance = new AddAdopCTR();
                }
            }
        }

        return mRongCloudInstance;
    }


    @Override
    public void doTask(AccessibilityEvent event) {
        mType = event.getEventType();
        mClassName = (String) event.getClassName();
        if (mType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED && mClassName.equals(Const.WXUI.LauncherUI)) {
            NLogger.d(TAG,"1.进入微信首页 点击通讯录按钮");
            sleepTime(2000);
            tagTextClick("通讯录");
            sleepTime(1000);
            NLogger.d(TAG,"2.到达通讯录界面 点击 新的朋友");
            tagTextClick("新的朋友");
        } else if (mType == AccessibilityEvent.TYPE_VIEW_SCROLLED && mClassName.equals(Const.LIST_VIEW)
                || mType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED && mClassName.equals(Const.WXUI.FMessageConversationUI)) {
            NLogger.d(TAG,"3.开始循环添加通讯录推荐好友");
            beginAddPeople();
        } else if (mType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED && mClassName.equals(Const.WXUI.ContactInfoUI)
                || mType == AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED && mClassName.equals(Const.TEXT_VIEW)) {
            NLogger.d(TAG,"3.开始循环添加通讯录推荐好友");
            peoPleInfoUI();
        } else if (mType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED && mClassName.equals(Const.WXUI.SayHiWithSnsPermissionUI)) {
            NLogger.d(TAG,"5.输入好友验证信息 添加好友");
            sleepTimedDefault();
            inputSayHiSentence(text);
            sleepTime(1500);
            RootShell.click(450,38);
        }
    }



    private void beginAddPeople() {
        AccessibilityNodeInfo scrllorNodeInfo = null;
        AccessibilityNodeInfo root = getRoot();
        if (root != null) {
            scrllorNodeInfo = NodeUtil.findNodeByClassNameAndTime(root, Const.LIST_VIEW, 1);

            List<AccessibilityNodeInfo> nodeByClassList = NodeUtil.findNodeByClassList(scrllorNodeInfo, Const.RELATIVE_LAYOUT);
            for (int i = 0; i < nodeByClassList.size(); i++) {

                if(currentAddCount == maxAddCount){
                    currentAddCount = 0;
                    stopTask();
                    return;
                }

                AccessibilityNodeInfo nodeInfo = nodeByClassList.get(i);
                if (nodeInfo != null && nodeInfo.getChildCount() >= 3) {
                    AccessibilityNodeInfo userNameNode = nodeInfo.getChild(0);
                    AccessibilityNodeInfo waitingValNode = nodeInfo.getChild(2);

                    Log.i(TAG, userNameNode.getText().toString());
                    Log.i(TAG, waitingValNode.getText().toString());

                    if (!mRecordMap.containsKey(userNameNode.getText().toString()) && waitingValNode.getText().toString().equals("接受")) {
                        AccessibilityNodeInfo clickNode = userNameNode;
                        while (clickNode != null && !clickNode.isClickable()) {
                            clickNode = clickNode.getParent();
                        }
                        if (clickNode != null) {
                            // mRecordMap.put(userNameNode.getText().toString(),true);
                            currentAddCount++;
                            NodeUtil.performClick(clickNode);
                            break;
                        }
                    }
                    if (i == nodeByClassList.size() - 1) {
                        if (scrllorNodeInfo != null) {
                            NodeUtil.performScroller(scrllorNodeInfo);
                            break;
                        }
                    }
                }

            }
        }
    }

    private void peoPleInfoUI() {
        AccessibilityNodeInfo root = getRoot();
        if (root != null) {
            String name =  findTextNodeInfoId("qj").getText().toString();
            //如果可以发消息，说明已经加为好友
            List<AccessibilityNodeInfo> sendBtnNodeList = root.findAccessibilityNodeInfosByText("发消息");
            if (sendBtnNodeList.size() > 0) {
                Log.e(TAG, "已经是好友无需添加,点击返回");
                mRecordMap.put(name,true);
                performBackClick();
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                return;
            }
            Log.d(TAG, "name:"+name);
            if (mRecordMap.containsKey(name) && mRecordMap.get(name)) {
                Log.e(TAG, "已经重复添加过,跳过点击返回");
                performBackClick();
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } else {
                if(currentAddCount  == maxAddCount){
                    currentAddCount = 0;
                    stopTask();
                    Log.e(TAG, "6.任务执行完毕停止任务");
                    return;
                    //停止任务
                }
                currentAddCount++;
                Log.e(TAG, "4.通过验证");
                boolean result = tagTextClick("通过验证");
                mRecordMap.put(name, result);
            }
        }
    }


    /**
     *
     * @param maxAddCount 同意的最大次数
     * @param minAddTime
     * @param maxAddTime
     * @param text       同意好友的时候 回复的话语
     */
    public void setParms(int maxAddCount,int minAddTime,int maxAddTime,String text){
        //  stopTask();
        EventBus.getDefault().post(new Boolean(true));
        PreferenceHelper.putBoolean(Const.PREF_KEY_STOP_AUTO_FLAG, true);
        this.maxAddCount = maxAddCount;
        this.minAddTime = minAddTime;
        this.maxAddTime = maxAddTime;
        this.currentAddCount = 0;
        this.text = text;
        mRecordMap.clear();

    }

}
